package com.db.utils;

import com.db.main.Constant;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.json.JSONObject;

public class Device {

    private static final Log log = LogFactory.getLog(Device.class);

    /**
     * 获取Android设备信息，并过滤gaid黑名单信息
     *
     * @param uuid          任务uuid
     * @param packageName   包名
     * @param isReal        是否使用真实设备
     * @param taskId        任务id
     * @param wbGaidOrderId gaid过滤标识
     * @return
     */
    public static String getAndroidDeviceInfo(String uuid, int taskId, String packageName, Boolean isReal, String wbGaidOrderId) {
        String deviceStr = "";
        int retry = 3;

        for (int i = 0; i < retry; i++) {
            deviceStr = getAndroidDeviceFromServer(uuid, packageName, isReal);

            if (deviceStr.isEmpty()) {
                // 设备信息为空时，循环获取
                continue;
            }

            if (wbGaidOrderId.isEmpty() || !isBlackGaid(uuid, deviceStr, taskId)) {
                return deviceStr;
            }
        }

        return deviceStr;
    }

    /**
     * 从后台获取Android设备信息
     * false:非随机设备. true:随机设备
     *
     * @param uuid        任务uuid
     * @param packageName 包名
     * @param isReal      是否使用真实设备
     * @return 设备信息
     */
    public static String getAndroidDeviceFromServer(String uuid, String packageName, Boolean isReal) {
        String getDeviceUrl = "";
        String deviceStr = "";

        try {
            // random=false，表示设备非随机
            if (isReal) {
                getDeviceUrl = String.format(Constant.REAL_ANDROID_DEVICE_URL, packageName);
            } else {
//                getDeviceUrl = String.format(Constant.VIRTUAL_ANDROID_DEVICE_URL, packageName, "false");
                getDeviceUrl = String.format(Constant.VIRTUAL_ANDROID_DEVICE_URL, packageName, "true");
            }

            LogUtil.logApp("getAndroidDeviceByServer", "获取设备URL：" + getDeviceUrl);

            LogUtil.logApp("getAndroidDeviceByServer", "uuid:" + uuid + ", 准备从服务器获取设备信息，url:" + getDeviceUrl);
            deviceStr = Downloader.doDownload(getDeviceUrl, "GET", null, null);
            LogUtil.logApp("getAndroidDeviceByServer", "uuid:" + uuid + ", Android deviceStr:" + deviceStr);

            // 当前任务使用设备已满时，random=true表示随机获取虚拟设备
            if (!isReal && deviceStr.contains("获取gaInfo 失败")) {
                getDeviceUrl = String.format(Constant.VIRTUAL_ANDROID_DEVICE_URL, packageName, "true");
                LogUtil.logApp("getAndroidDeviceByServer", "uuid:" + uuid + ", 获取设备信息异常，准备再次从服务器获取设备信息，url:" + getDeviceUrl);
                deviceStr = Downloader.doDownload(getDeviceUrl, "GET", null, null);
                LogUtil.logApp("getAndroidDeviceByServer", "uuid:" + uuid + ", Android deviceStr:" + deviceStr);
            }
        } catch (Exception e) {
            LogUtil.logApp("getAndroidDeviceByServer Exception", "uuid:" + uuid + ", 获取Android随机设备异常：" + e.getMessage());
            e.printStackTrace();
        }
        return deviceStr;
    }

    /**
     * 判断 gaid 是否属于黑名单
     *
     * @param deviceStr 设备信息
     * @param taskId    任务id
     * @return
     */
    public static boolean isBlackGaid(String uuid, String deviceStr, int taskId) {

        try {
            JSONObject respJSON = new JSONObject(deviceStr);
            int respCode = respJSON.getInt("code");
            if (respCode != 200) {
                return false;
            }
            JSONObject deviceJson = respJSON.getJSONObject("data");
            JSONObject gaJson = deviceJson.getJSONObject("gaInfo");
            String gaid = gaJson.getString("gaId");
            if (gaid.isEmpty()) {
                return false;
            }

            // 判断gaid是否属于黑名单
            String filterResult = Downloader.doDownload(
                    String.format(Constant.VERIFY_GAID_BLACKLIST, gaid, taskId),
                    "GET", null, null);

            // 1：属于黑名单，0：不属于黑名单
            if ("1".equals(filterResult)) {
                LogUtil.logApp("DeviceInfo", "uuid:" + uuid + "，gaid属于黑名单，需要重新获取..." + gaid);
                return true;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return false;
    }

}
